package com.adams.action.audit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.DynaBean;

import com.adams.access.db.bean.AuditStep;
import com.adams.access.db.bean.Parameter;
import com.adams.access.db.bean.User;
import com.adams.audit.common.AuditConstants;
import com.adams.audit.config.service.IAuditStepService;
import com.adams.audit.web.bean.AuditType;
import com.adams.common.BaseAction;
import com.adams.custom.page.mgt.service.ViewParseService;
import com.adams.custom.page.util.ViewConstant;
import com.adams.sys.parameter.service.ParameterService;
import com.adams.user.service.UserService;
import com.adams.utils.Page;


/**
 * 
 * 
 * File Name : AuditStepAction.java
 * 
 * @Description : 审核步骤配置action
 * @author 904304 张益民
 */
public class AuditStepAction extends BaseAction
{

	private static final long serialVersionUID = -2717702424369713400L;

	private ViewParseService viewParseService;

	private IAuditStepService auditStepService;

	private UserService userService;

	private ParameterService parameterService;

	/**
	 * 
	 * Description : 获取所有类型 request{}
	 * 
	 */
	public void getAllType() throws Exception
	{
		List<AuditType> list = auditStepService.getAllType();

		write("{\"data\":" + JSONArray.fromObject(list).toString() + "}");
	}

	/**
	 * 
	 * Description : 获取步骤配置表 request{typeCode,step}
	 * step为"0"或null，则查询数据库中的数据返回给页面 step不为"0"或null，则造相应个步骤数据的给页面
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void getStepConfig() throws Exception
	{
		String typeCode = request.getParameter("typeCode");
		String step = request.getParameter("step");
		List<Map> tempList = new ArrayList<Map>();

		int stepNum = step != null ? Integer.valueOf(step) : 0;

		if (stepNum == 0)
		{
			List<AuditStep> list = auditStepService
					.listAllStepsByType(typeCode);
			for (AuditStep auditStep : list)
			{
				Map tempBean = new HashMap();
				tempBean.put("step", auditStep.getStep());
				tempBean.put("userId", auditStep.getUser().getId());
				tempBean.put("userName", auditStep.getUser().getUserName());
				tempBean.put("typeCode", auditStep.getTypeCode());
				tempList.add(tempBean);
			}

		} else
		{

			for (int i = 0; i < stepNum; i++)
			{
				Map tempBean = new HashMap();
				tempBean.put("step", i + 1);
				tempBean.put("typeCode", typeCode);
				tempList.add(tempBean);
			}
		}
		write("{\"data\":" + JSONArray.fromObject(tempList).toString() + "}");
	}

	/**
	 * 
	 * Description : 获取步骤下拉框数据 request{}
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void getStepArray() throws Exception
	{
		int maxStep = 10;
		Parameter parameter = parameterService.queryByTypeAndName(
				AuditConstants.SYS_AUDIT_CODE, AuditConstants.MAX_STEP);
		try
		{
			if (parameter != null)
				maxStep = Integer.valueOf(parameter.getParameterValue());
		} catch (Exception e)
		{
			maxStep = AuditConstants.DEFAULT_MAX_STEP;
		}
		List<String> list = auditStepService.createStepNo(maxStep);
		List<Map> tempList = new ArrayList<Map>();
		for (String step : list)
		{
			Map tempBean = new HashMap();
			tempBean.put("text", step);
			tempBean.put("value", step);
			tempList.add(tempBean);
		}

		write("{\"stepSelect\":" + JSONArray.fromObject(tempList).toString()
				+ "}");
	}

	/**
	 * 
	 * Description : 保存审核步骤配置信息 request{typeCode,data}
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void saveStepConfig() throws Exception
	{
		String data = request.getParameter("data");
		String typeCode = request.getParameter("typeCode");
		String flag = request.getParameter("flag");

		if (data != null)
		{
			JSONArray jsonArray = JSONArray.fromObject(data);
			List<DynaBean> list = (List<DynaBean>) JSONArray
					.toCollection(jsonArray);
			List<AuditStep> auditStepList = new ArrayList<AuditStep>();
			for (DynaBean dynaBean : list)
			{
				AuditStep auditStep = new AuditStep();
				auditStep.setStep((Integer) dynaBean.get("step"));
				auditStep.setTypeCode(typeCode);
				auditStep.setUser(userService.queryById(((Integer) dynaBean
						.get("userId")).longValue()));
				auditStepList.add(auditStep);
			}
			boolean success = false;
			if (flag != null && flag.equalsIgnoreCase("part"))
			// 部分更新
			{
				success = auditStepService
						.updateAuditStepForType(auditStepList);
			} else
			// 全部更新
			{
				success = auditStepService.saveAuditStepForType(auditStepList);
			}

			// 记录日志
			createLog("saveStepConfig", "AuditStep typeCode:" + typeCode);

			if (success)
			{
				sendSuccessMessage("保存成功!");
			} else
			{
				sendFailureMessage("保存失败!");
			}
		}
	}

	/**
	 * 
	 * Description : 获取用户列表 request{pageNo,pageSize,userName,realName}
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void listUser() throws Exception
	{
		String start = request.getParameter(ViewConstant.JSON_PAGE_START);
		String limit = request.getParameter(ViewConstant.JSON_PAGE_LIMIT);
		int pageSize = limit != null ? Integer.parseInt(limit) : 10;
		int startNo = start != null ? Integer.parseInt(start) : 0;
		String userName = request.getParameter("userName");
		String realName = request.getParameter("realName");

		Page<User> page = new Page<User>();
		page.setPageSize(pageSize);
		page.setBeginCount(startNo);
		page = userService.queryAllByPage(page, userName, realName);
		List<User> list = page.getResultList();
		List<Map> tempList = new ArrayList<Map>();
		for (User user : list)
		{
			Map userBean = new HashMap();
			userBean.put("id", user.getId());
			userBean.put("userName", user.getUserName());
			userBean.put("realName", user.getRealName());
			tempList.add(userBean);
		}
		List<Map> fieldMapList = new ArrayList();
		Map field1 = new HashMap();
		Map field2 = new HashMap();
		Map field3 = new HashMap();
		field1.put("name", "id");
		field1.put("type", "int");
		field1.put("header", "用户id");
		field2.put("name", "userName");
		field2.put("type", "string");
		field2.put("header", "用户名称");
		field3.put("name", "realName");
		field3.put("type", "string");
		field3.put("header", "真实姓名");
		fieldMapList.add(field1);
		fieldMapList.add(field2);
		fieldMapList.add(field3);
		Map map = organiseResult(true, fieldMapList, tempList, page
				.getTotalCount());

		write(JSONObject.fromObject(map).toString());

	}

	/**
	 * 
	 * Description : 为页面提供响应事件
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void listEvent() throws Exception
	{
		List<Map> fieldMapList = new ArrayList();
		Map field1 = new HashMap();
		Map field2 = new HashMap();
		Map field3 = new HashMap();
		field1.put("name", "id");
		field1.put("header", "用户id");
		field2.put("name", "userName");
		field2.put("header", "用户名称");
		field3.put("name", "realName");
		field3.put("header", "真实姓名");
		fieldMapList.add(field1);
		fieldMapList.add(field2);
		fieldMapList.add(field3);

		List lisenters = new ArrayList();
		Map lisenter = new HashMap();
		lisenter.put("actionType", "rowdblclick");
		lisenters.add(lisenter);
		Map map = organiseEvent(true, fieldMapList, lisenters);

		write(JSONObject.fromObject(map).toString());
	}

	/**
	 * 
	 * Description : 显示布局
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	public String listPanel() throws Exception
	{
		long menuId = request.getParameter("menuId") != null ? Long
				.valueOf(request.getParameter("menuId")) : 0;
		write(viewParseService.getParseViewJSONByMenuId(getUserId(), menuId));
		return null;
	}

	/**
	 * 
	 * Description : 为列表页面组装数据结构
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private Map organiseResult(boolean success, List<Map> fieldMapList,
			List records, int total)
	{
		List fields = new ArrayList();
		List columns = new ArrayList();
		for (Map temp : fieldMapList)
		{
			Map field = new HashMap();
			Map column = new HashMap();
			field.put("name", temp.get("name"));
			field.put("type", temp.get("type"));
			column.put("header", temp.get("header"));
			column.put("dataIndex", temp.get("name"));
			fields.add(field);
			columns.add(column);
		}
		Map metaData = new HashMap();
		metaData.put("totalProperty", "total");
		metaData.put("root", "records");
		metaData.put("id", "id");
		metaData.put("fields", fields);

		Map map = new HashMap();
		map.put("success", success);
		map.put("metaData", metaData);
		map.put("total", total);
		map.put("records", records);
		map.put("columns", columns);
		return map;
	}

	/**
	 * 
	 * Description : 为页面组装事件结构
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private Map organiseEvent(boolean success, List<Map> fieldMapList,
			List lisenters)
	{
		List columns = new ArrayList();
		for (Map temp : fieldMapList)
		{
			Map column = new HashMap();
			column.put("header", temp.get("header"));
			column.put("dataIndex", temp.get("name"));
			columns.add(column);
		}
		Map map = new HashMap();
		map.put("success", success);
		map.put("lisenters", lisenters);
		map.put("columns", columns);
		return map;
	}

	/*********************** 属性设置 ***********************/

	public IAuditStepService getAuditStepService()
	{
		return auditStepService;
	}

	public void setAuditStepService(IAuditStepService auditStepService)
	{
		this.auditStepService = auditStepService;
	}

	public UserService getUserService()
	{
		return userService;
	}

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}

	public ParameterService getParameterService()
	{
		return parameterService;
	}

	public void setParameterService(ParameterService parameterService)
	{
		this.parameterService = parameterService;
	}

	public ViewParseService getViewParseService()
	{
		return viewParseService;
	}

	public void setViewParseService(ViewParseService viewParseService)
	{
		this.viewParseService = viewParseService;
	}

}
